#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
需求验证脚本
验证WebSocket代理桥接服务是否满足所有规格要求
"""

import os
import ast
import logging
import json
from typing import List, Dict, Any

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class RequirementValidator:
    """需求验证器"""
    
    def __init__(self):
        self.validation_results = {}
        self.main_script = 'websocket_proxy_bridge.py'
    
    def validate_requirement_1(self) -> bool:
        """验证需求1: WebSocket连接拦截功能"""
        logger.info("验证需求1: WebSocket连接拦截功能")
        
        checks = {
            "1.1 WebSocket连接建立拦截": self._check_websocket_start_handler(),
            "1.2 消息完整性和顺序保持": self._check_message_forwarding(),
            "1.3 多连接并发处理": self._check_concurrent_connections()
        }
        
        all_passed = all(checks.values())
        self.validation_results['requirement_1'] = {
            'passed': all_passed,
            'details': checks
        }
        
        for check, result in checks.items():
            status = "✓" if result else "✗"
            logger.info(f"  {status} {check}")
        
        return all_passed
    
    def validate_requirement_2(self) -> bool:
        """验证需求2: 透明代理功能"""
        logger.info("验证需求2: 透明代理功能")
        
        checks = {
            "2.1 客户端到服务端消息转发": self._check_client_to_server_forwarding(),
            "2.2 服务端到客户端消息转发": self._check_server_to_client_forwarding(),
            "2.3 连接关闭处理": self._check_connection_close_handling()
        }
        
        all_passed = all(checks.values())
        self.validation_results['requirement_2'] = {
            'passed': all_passed,
            'details': checks
        }
        
        for check, result in checks.items():
            status = "✓" if result else "✗"
            logger.info(f"  {status} {check}")
        
        return all_passed
    
    def validate_requirement_3(self) -> bool:
        """验证需求3: HTTP接口功能"""
        logger.info("验证需求3: HTTP接口功能")
        
        checks = {
            "3.1 HTTP请求参数接收": self._check_http_request_handling(),
            "3.2 消息发送到WebSocket": self._check_message_sending(),
            "3.3 错误响应处理": self._check_error_responses(),
            "3.4 连接不存在错误": self._check_connection_not_found_error()
        }
        
        all_passed = all(checks.values())
        self.validation_results['requirement_3'] = {
            'passed': all_passed,
            'details': checks
        }
        
        for check, result in checks.items():
            status = "✓" if result else "✗"
            logger.info(f"  {status} {check}")
        
        return all_passed
    
    def validate_requirement_4(self) -> bool:
        """验证需求4: 代码质量要求"""
        logger.info("验证需求4: 代码质量要求")
        
        checks = {
            "4.1 代码精简性": self._check_code_conciseness(),
            "4.2 中文注释完整性": self._check_chinese_comments(),
            "4.3 配置选项": self._check_configuration_options(),
            "4.4 日志输出": self._check_logging_implementation()
        }
        
        all_passed = all(checks.values())
        self.validation_results['requirement_4'] = {
            'passed': all_passed,
            'details': checks
        }
        
        for check, result in checks.items():
            status = "✓" if result else "✗"
            logger.info(f"  {status} {check}")
        
        return all_passed
    
    def validate_requirement_5(self) -> bool:
        """验证需求5: 连接管理功能"""
        logger.info("验证需求5: 连接管理功能")
        
        checks = {
            "5.1 连接状态查询": self._check_connection_status_query(),
            "5.2 连接事件记录": self._check_connection_event_logging(),
            "5.3 连接断开功能": self._check_connection_disconnect()
        }
        
        all_passed = all(checks.values())
        self.validation_results['requirement_5'] = {
            'passed': all_passed,
            'details': checks
        }
        
        for check, result in checks.items():
            status = "✓" if result else "✗"
            logger.info(f"  {status} {check}")
        
        return all_passed
    
    def _check_websocket_start_handler(self) -> bool:
        """检查WebSocket连接建立处理"""
        return self._check_method_exists('WebSocketInterceptor', 'websocket_start')
    
    def _check_message_forwarding(self) -> bool:
        """检查消息转发功能"""
        return self._check_method_exists('WebSocketInterceptor', 'websocket_message')
    
    def _check_concurrent_connections(self) -> bool:
        """检查并发连接处理"""
        return self._check_class_exists('ConnectionManager') and self._check_thread_safety()
    
    def _check_client_to_server_forwarding(self) -> bool:
        """检查客户端到服务端转发"""
        return self._check_method_exists('WebSocketInterceptor', 'websocket_message')
    
    def _check_server_to_client_forwarding(self) -> bool:
        """检查服务端到客户端转发"""
        return self._check_method_exists('WebSocketInterceptor', 'websocket_message')
    
    def _check_connection_close_handling(self) -> bool:
        """检查连接关闭处理"""
        return self._check_method_exists('WebSocketInterceptor', 'websocket_end')
    
    def _check_http_request_handling(self) -> bool:
        """检查HTTP请求处理"""
        return self._check_method_exists('HTTPAPIServer', 'send_message') or self._check_class_exists('HTTPAPIServer')
    
    def _check_message_sending(self) -> bool:
        """检查消息发送功能"""
        return self._check_method_exists('ConnectionManager', 'send_message')
    
    def _check_error_responses(self) -> bool:
        """检查错误响应处理"""
        return self._check_error_handling_in_api()
    
    def _check_connection_not_found_error(self) -> bool:
        """检查连接不存在错误处理"""
        return self._check_404_error_handling()
    
    def _check_code_conciseness(self) -> bool:
        """检查代码精简性"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 检查代码行数是否合理（不超过1000行）
        code_lines = [line for line in lines if line.strip() and not line.strip().startswith('#')]
        return len(code_lines) <= 1000
    
    def _check_chinese_comments(self) -> bool:
        """检查中文注释完整性"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否包含中文注释
        chinese_comment_indicators = ['"""', "'''", '#']
        has_chinese = ('中' in content or '的' in content or '是' in content)
        has_comments = any(indicator in content for indicator in chinese_comment_indicators)
        
        return has_chinese and has_comments
    
    def _check_configuration_options(self) -> bool:
        """检查配置选项"""
        return self._check_class_exists('Config') and self._check_argparse_usage()
    
    def _check_logging_implementation(self) -> bool:
        """检查日志实现"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return 'logging' in content and 'logger' in content
    
    def _check_connection_status_query(self) -> bool:
        """检查连接状态查询"""
        return self._check_method_exists('ConnectionManager', 'get_active_connections')
    
    def _check_connection_event_logging(self) -> bool:
        """检查连接事件记录"""
        return self._check_class_exists('SystemMonitor')
    
    def _check_connection_disconnect(self) -> bool:
        """检查连接断开功能"""
        return self._check_method_exists('ConnectionManager', 'unregister_connection')
    
    def _check_method_exists(self, class_name: str, method_name: str) -> bool:
        """检查类方法是否存在"""
        if not os.path.exists(self.main_script):
            return False
        
        try:
            with open(self.main_script, 'r', encoding='utf-8') as f:
                tree = ast.parse(f.read())
            
            for node in ast.walk(tree):
                if isinstance(node, ast.ClassDef) and node.name == class_name:
                    for item in node.body:
                        if isinstance(item, ast.FunctionDef) and item.name == method_name:
                            return True
            return False
        except Exception:
            return False
    
    def _check_class_exists(self, class_name: str) -> bool:
        """检查类是否存在"""
        if not os.path.exists(self.main_script):
            return False
        
        try:
            with open(self.main_script, 'r', encoding='utf-8') as f:
                tree = ast.parse(f.read())
            
            for node in ast.walk(tree):
                if isinstance(node, ast.ClassDef) and node.name == class_name:
                    return True
            return False
        except Exception:
            return False
    
    def _check_thread_safety(self) -> bool:
        """检查线程安全性"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return 'threading.Lock' in content or 'lock' in content.lower()
    
    def _check_error_handling_in_api(self) -> bool:
        """检查API错误处理"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return 'try:' in content and 'except' in content and 'status=400' in content
    
    def _check_404_error_handling(self) -> bool:
        """检查404错误处理"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return 'status=404' in content
    
    def _check_argparse_usage(self) -> bool:
        """检查命令行参数解析"""
        if not os.path.exists(self.main_script):
            return False
        
        with open(self.main_script, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return 'argparse' in content and 'ArgumentParser' in content
    
    def validate_file_completeness(self) -> bool:
        """验证文件完整性"""
        logger.info("验证文件完整性")
        
        required_files = [
            'websocket_proxy_bridge.py',
            'test_websocket_server.py',
            'test_websocket_client.py',
            'test_http_api.py',
            'run_tests.py',
            'example_usage.py',
            'quick_start.py',
            'requirements.txt',
            'README.md'
        ]
        
        missing_files = []
        for file in required_files:
            if os.path.exists(file):
                logger.info(f"  ✓ {file}")
            else:
                logger.info(f"  ✗ {file} (缺失)")
                missing_files.append(file)
        
        return len(missing_files) == 0
    
    def run_validation(self) -> bool:
        """运行完整验证"""
        logger.info("=" * 60)
        logger.info("开始需求验证")
        logger.info("=" * 60)
        
        # 验证文件完整性
        files_complete = self.validate_file_completeness()
        
        if not files_complete:
            logger.error("文件不完整，跳过功能验证")
            return False
        
        logger.info("-" * 40)
        
        # 验证各项需求
        req1_passed = self.validate_requirement_1()
        req2_passed = self.validate_requirement_2()
        req3_passed = self.validate_requirement_3()
        req4_passed = self.validate_requirement_4()
        req5_passed = self.validate_requirement_5()
        
        # 总结结果
        logger.info("=" * 60)
        logger.info("验证结果总结")
        logger.info("=" * 60)
        
        requirements = [
            ("需求1: WebSocket连接拦截", req1_passed),
            ("需求2: 透明代理功能", req2_passed),
            ("需求3: HTTP接口功能", req3_passed),
            ("需求4: 代码质量要求", req4_passed),
            ("需求5: 连接管理功能", req5_passed)
        ]
        
        passed_count = 0
        for req_name, passed in requirements:
            status = "✓ 通过" if passed else "✗ 失败"
            logger.info(f"{req_name}: {status}")
            if passed:
                passed_count += 1
        
        overall_success = passed_count == len(requirements)
        
        logger.info("-" * 40)
        logger.info(f"总体结果: {passed_count}/{len(requirements)} 项需求通过")
        
        if overall_success:
            logger.info("🎉 所有需求验证通过！")
        else:
            logger.warning("⚠️  部分需求验证失败，请检查实现")
        
        logger.info("=" * 60)
        
        return overall_success


def main():
    """主函数"""
    validator = RequirementValidator()
    success = validator.run_validation()
    
    # 保存验证结果
    with open('validation_results.json', 'w', encoding='utf-8') as f:
        json.dump(validator.validation_results, f, indent=2, ensure_ascii=False)
    
    logger.info("验证结果已保存到 validation_results.json")
    
    exit_code = 0 if success else 1
    return exit_code


if __name__ == "__main__":
    exit(main())